"""
配置管理模块
"""
import os
from dataclasses import dataclass
from typing import Optional
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# Coze API 基础 URL
COZE_CN_BASE_URL = "https://api.coze.cn"


@dataclass
class OSSConfig:
    """阿里云 OSS 配置"""
    access_key_id: str
    access_key_secret: str
    endpoint: str
    bucket_name: str

    @classmethod
    def from_env(cls) -> Optional['OSSConfig']:
        """从环境变量创建配置"""
        access_key_id = os.getenv('OSS_ACCESS_KEY_ID')
        access_key_secret = os.getenv('OSS_ACCESS_KEY_SECRET')
        endpoint = os.getenv('OSS_ENDPOINT')
        bucket_name = os.getenv('OSS_BUCKET_NAME')

        if all([access_key_id, access_key_secret, endpoint, bucket_name]):
            return cls(access_key_id, access_key_secret, endpoint, bucket_name)
        return None

    @property
    def is_valid(self) -> bool:
        """检查配置是否有效"""
        return all([
            self.access_key_id,
            self.access_key_secret,
            self.endpoint,
            self.bucket_name
        ])


@dataclass
class CozeConfig:
    """Coze 配置"""
    api_token: str
    api_base: str
    workflow_id: str

    @classmethod
    def from_env(cls) -> Optional['CozeConfig']:
        """从环境变量创建配置"""
        api_token = os.getenv('COZE_API_TOKEN')
        api_base = os.getenv('COZE_API_BASE', COZE_CN_BASE_URL)
        workflow_id = os.getenv('COZE_WORKFLOW_ID')

        if all([api_token, workflow_id]):
            return cls(api_token, api_base, workflow_id)
        return None

    @property
    def is_valid(self) -> bool:
        """检查配置是否有效"""
        return all([
            self.api_token,
            self.api_base,
            self.workflow_id
        ])


@dataclass
class AppConfig:
    """应用配置"""
    max_content_length: int = 16 * 1024 * 1024  # 16MB
    temp_file_expiry_hours: int = 24
    allowed_extensions: set = None

    def __post_init__(self):
        if self.allowed_extensions is None:
            self.allowed_extensions = {'txt', 'pdf', 'doc', 'docx', 'xlsx', 'xls'}

        # 从环境变量获取最大内容长度
        max_length = os.getenv('MAX_CONTENT_LENGTH')
        if max_length:
            self.max_content_length = int(max_length)
